package com.example.test15_2;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Thread thread;//声明一个线程对象
    private static MediaPlayer mp = null;//声明一个MediaPlayer对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button start = (Button) findViewById(R.id.start);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((Button) view).setEnabled(false);//设置按钮不可用
                //创建一个用于播放背景音乐的线程
                thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        playBGSound();//播放背景音乐
                    }
                });
                thread.start();//开启线程
            }
        });
    }

    private void playBGSound() {
        if (mp != null){
            mp.release();//释放资源
        }
        mp = MediaPlayer.create(MainActivity.this,R.raw.perfect);
        mp.start();//开始播放
        //为MediaPlayer添加播放完成事件监听器
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                try {
                    Thread.sleep(5000);//线程休眠5s
                    playBGSound();//重新播放音乐
                }catch (InterruptedException e ){
                    e.printStackTrace();
                }
            }
        });
    }
    @Override
    protected void onDestroy(){
        if(mp != null){
            mp.stop();//停止播放
            mp.release();//释放资源
            mp = null;
        }
        if (thread != null){
            thread = null;
        }
        super.onDestroy();
    }
}